﻿using System;
using System.Net.Sockets;
using System.Threading;

namespace UDFSocket
{
    /// <summary>
    /// 异步写状态对象
    /// </summary>
    internal class AsyncWriteStateObject
    {
        public ManualResetEvent eventDone;
        public Exception exception;
        public SocketPlus workSocket;
        public int sendedCount;
    }

    /// <summary>
    /// 实现TcpClient的异步发送
    /// </summary>
    public partial class SocketPlus
    {
        /// <summary>
        /// 设置写超时等待值
        /// </summary>
        public Int32 WriteTimeout = Timeout.Infinite;

        /// <summary>
        /// 异步发送
        /// </summary>
        /// <param name="buffer">字节数组</param>
        /// <param name="offset">起始偏移量</param>
        /// <param name="size">字节数</param>
        public void Write(Byte[] buffer, Int32 offset, Int32 size)
        {
            // 用户定义对象
            AsyncWriteStateObject State = new AsyncWriteStateObject
            {   // 将事件状态设置为非终止状态，导致线程阻止
                eventDone = new ManualResetEvent(false),
                exception = null,
                workSocket = this
            };
            // 写入加长度信息头的数据
            BeginSend(buffer,
                offset,
                size,
                SocketFlags.None,
                new AsyncCallback(AsyncWriteCallback),
                State);
            // 等待操作完成信号
            if (State.eventDone.WaitOne(WriteTimeout, false))
            {   // 接收到信号
                if (State.exception != null) throw State.exception;
            }
            else
            {   // 超时异常
                throw new TimeoutException();
            }
        }


        /// <summary>
        /// 异步写入回调函数
        /// </summary>
        /// <param name="ar">异步操作结果</param>
        private static void AsyncWriteCallback(IAsyncResult ar)
        {
            AsyncWriteStateObject State = ar.AsyncState as AsyncWriteStateObject;
            try
            {   // 异步写入结束
                State.sendedCount = State.workSocket.EndSend(ar);
            }

            catch (Exception e)
            {   // 异步连接异常
                State.exception = e;
            }

            finally
            {   // 将事件状态设置为终止状态，线程继续
                State.eventDone.Set();
            }
        }
    }
}
